#coding=utf-8
from decimal import Decimal

import utility as u

class TradableShare(object):
    '''可流通股的数量'''
    def __init__(self, code=None):
        self.code = code
        self.tss = []
        
    def append_ts(self, date, quatity):
        self.tss.append([date, quatity])
    
    def toDict(self):
        tss = sorted(self.tss, lambda x,y: cmp(x[0], y[0]) )
        #print tss
        return {self.code: tss}
            
def get_ts_from_table(table):
    data = []
    cs = table.contents
    
    d = []
    for td in cs[1].contents[1:]:
        date = td.string
        d.append(date.encode('u8'))
    data.append(d)
  
    d = []
    for td in cs[7].contents[1:]:
        d.append(td.string)
    d = [i[:-2].encode('u8') for i in d if i]
    d = [  str( int (Decimal(i) * 10000) )  for i in d]
    data.append(d)
    
    data = zip(*data)        
    
    result = []
    for d in data:
        if d[-1] == '0':continue
        result.append(list(d))
    
    return result

def get_ts_from_soup(soup):
    #print soup
    data = []
    t = unicode('变动日期', 'u8')
    bds = soup.findAll(text= lambda(x): x.find( t )!=-1)
    #print len(bds)
    
    #i = 0
    for bd in bds:
        #i = i + 1
        table = bd.parent.parent.parent
        #print i
        d = get_ts_from_table(table)
        data.extend(d)
        
    return data

def get_ts(code):
    '''获取上市公司流通A股数量'''
    url = 'http://money.finance.sina.com.cn/corp/go.php/vCI_StockStructure/stockid/%s.phtml'%code
    s = u.get_soup(url)
    data = get_ts_from_soup(s)
    
    ts = TradableShare(code)
    for i in data:
        d, q = i
        ts.append_ts(d, q)    
        
    r = ts.toDict()
    
    return r
